var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressJWT = require('express-jwt')

require('dotenv').config()
// 数据库连接
require('./dao/db')

// 路由
var adminRouter = require('./routes/admin');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// token验证
app.use(expressJWT({
  secret:md5(process.env["DB_SECRET"]),
  algorithms:['HS256'],
}).unless({
  path:[
    {"url":"/api/admin/login"}
  ]
})  )

// 路由中间件
app.use('/api/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  if(err.name === 'UnauthorizeError') {
    res.send()
  }
});

module.exports = app;
